'use strict';

const { DataTypes } = require('sequelize');
const sequelize = require('../../database/sequelize');
const Budget = require('./budget');
const User = require('./user');

const Expense = sequelize.define(
    'Expense',
    {
        id: {
            type: DataTypes.INTEGER.UNSIGNED,
            primaryKey: true,
            autoIncrement: true,
            comment: '支出记录ID',
        },
        budget_id: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '所属预算ID',
        },
        user_id: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '所属用户ID',
        },
        category: {
            type: DataTypes.STRING(50),
            allowNull: false,
            comment: '分类，如住宿/餐饮/交通等',
        },
        amount: {
            type: DataTypes.DECIMAL(10, 2),
            allowNull: false,
            defaultValue: 0,
            comment: '支出金额',
        },
        currency: {
            type: DataTypes.STRING(10),
            allowNull: false,
            defaultValue: 'CNY',
            comment: '币种',
        },
        date: {
            type: DataTypes.DATEONLY,
            allowNull: false,
            comment: '发生日期',
        },
        description: {
            type: DataTypes.TEXT,
            allowNull: true,
            comment: '备注描述',
        },
    },
    {
        tableName: 'expenses',
        timestamps: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        underscored: true,
    }
);

Expense.belongsTo(Budget, { foreignKey: 'budget_id', as: 'budget', onDelete: 'CASCADE' });
Budget.hasMany(Expense, { foreignKey: 'budget_id', as: 'expenses', onDelete: 'CASCADE' });
Expense.belongsTo(User, { foreignKey: 'user_id', as: 'user' });

module.exports = Expense;

// 初始化表与开发环境种子数据
(async () => {
    try {
        // await Expense.sync({ alter: true });

        if (process.env.NODE_ENV !== 'production') {
            const count = await Expense.count();
            if (count === 0) {
                const budget = await Budget.findOne({ order: [['id', 'ASC']] });
                const user = await User.findOne({ order: [['id', 'ASC']] });
                if (budget && user) {
                    const budgetId = budget.id;
                    const userId = user.id;
                    await Expense.bulkCreate([
                        { id: 1, budget_id: budgetId, user_id: userId, category: '住宿', amount: 300, date: '2025-10-15', description: '青年旅舍住宿' },
                        { id: 2, budget_id: budgetId, user_id: userId, category: '住宿', amount: 300, date: '2025-10-16', description: '青年旅舍住宿' },
                        { id: 3, budget_id: budgetId, user_id: userId, category: '住宿', amount: 300, date: '2025-10-17', description: '青年旅舍住宿' },
                        { id: 4, budget_id: budgetId, user_id: userId, category: '餐饮', amount: 150, date: '2025-10-15', description: '午餐和晚餐' },
                        { id: 5, budget_id: budgetId, user_id: userId, category: '餐饮', amount: 200, date: '2025-10-16', description: '一日三餐' },
                        { id: 6, budget_id: budgetId, user_id: userId, category: '餐饮', amount: 300, date: '2025-10-17', description: '火锅晚餐' },
                        { id: 7, budget_id: budgetId, user_id: userId, category: '交通', amount: 120, date: '2025-10-15', description: '机场到市区打车' },
                        { id: 8, budget_id: budgetId, user_id: userId, category: '交通', amount: 200, date: '2025-10-16', description: '市区交通' },
                        { id: 9, budget_id: budgetId, user_id: userId, category: '门票', amount: 230, date: '2025-10-16', description: '熊猫基地门票' },
                    ]);
                    console.log('✅ 已插入示例支出数据');
                }
            }
        }
    } catch (e) {
        console.error('Expense 模型初始化失败:', e);
    }
})();